package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ben.huang
 */
@Configuration
public class ExecutorConfig {

    @Bean
    public ThreadPoolTaskExecutor singleThreadPool(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数量一般为cpu核数*2
        threadPoolTaskExecutor.setCorePoolSize(1);
        //最大线程池数量
        threadPoolTaskExecutor.setMaxPoolSize(1);
        //队列中最大的任务数量
        threadPoolTaskExecutor.setQueueCapacity(1);
        //线程名称的前缀
        threadPoolTaskExecutor.setThreadNamePrefix("SingleThreadPool-");
        //拒绝策略
        // abortPolicy-默认直接拒绝并抛出异常
        // callerRunsPolicy-在调用者线程中直接执行档期那被丢弃的任务
        // discardOldestPolicy-丢弃最老的请求，也就是即将被执行的任务
        // discardPolicy-直接丢弃无法处理的任务，不做任何处理
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //线程空闲的最大存活时常
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //初始化线程池
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;


    }
}
